package com.xframe.domain;

import com.xframe.domain.repository.SysBaseRepository;
import com.xframe.domain.sys.SysModel;
import com.xframe.domain.sys.SysModelBaseRepository;

import java.util.HashMap;
import java.util.Map;

public class ModelRepositoryFactory {

    private static Map<String,Object> cache = new HashMap<>();


    public static <T extends SysBaseRepository> T builder(SysModel sysModel){
        if(!cache.containsKey(sysModel.getModelCode())){
            SysModelBaseRepository sysModelBaseRepository = SysModelBaseRepository.getInstance(sysModel.getModelId());

            T obj = (T) toSysBaseRepository(sysModelBaseRepository,sysModel);
            cache.put(sysModel.getModelCode(),obj);
        }
        return (T) cache.get(sysModel.getModelCode());
    }

    public static <T extends SysBaseRepository> T builder(Class<?> dataType){

        if(!cache.containsKey(dataType.getName())){
            SysModelBaseRepository sysModelBaseRepository = SysModelBaseRepository.getInstance(dataType.getName());
            SysModel sysModel = SysModel.getInstance(dataType.getName());
            T obj = (T) toSysBaseRepository(sysModelBaseRepository,sysModel);
            cache.put(dataType.getName(),obj);
        }
        return (T) cache.get(dataType.getName());
    }


    private static SysBaseRepository toSysBaseRepository(SysModelBaseRepository sysModelBaseRepository,SysModel sysModel){
        try {

            if (sysModel == null) {
                return new SysBaseRepository();
            }
            if (sysModelBaseRepository == null) {
                SysBaseRepository repository = new SysBaseRepository();
                repository.setDsCode(sysModel.getDataSourceDefCode());
                repository.init();
                return repository;
            }
            String typeName = sysModelBaseRepository.getClassName();
            SysBaseRepository sysBaseRepository = (SysBaseRepository)Class.forName(typeName).newInstance();
            sysBaseRepository.setDsCode(sysModel.getDataSourceDefCode());
            sysBaseRepository.init();
            return sysBaseRepository;
        }catch (Exception ex){
            SysBaseRepository repository = new SysBaseRepository();
            repository.init();
            return repository;
        }
    }
}
